package com.veetao.api.msgqueue;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;

/**
 * 队列消息处理器
 * 
 * @author guohongtao
 * @date 2016年8月1日
 */

@Component
public class ActionHandler {

	private static Log logger = LogFactory.getLog(ActionHandler.class);

	private Map<Class<? extends AbstractAction>, List<ActionConsumer<? extends AbstractAction>>> actionConsumers = new HashMap<Class<? extends AbstractAction>, List<ActionConsumer<? extends AbstractAction>>>();

	public void handleMessage(Object message) {
		if (!AbstractAction.class.isInstance(message)) {
			logger.error("Unrecognized message: " + message);
			return;
		}
		AbstractAction action = (AbstractAction) message;
		logger.info(
				String.format("handle message: [%s], data: %s ", action.getClass().getSimpleName(), action.toString()));

		try {
			Class<? extends AbstractAction> actionClass = action.getClass();
			logger.info("action class：" + actionClass.getName());
			List<ActionConsumer<? extends AbstractAction>> consumers = actionConsumers.get(actionClass);
			if (consumers != null && consumers.size() > 0) {
				/* 逐个调用消费对象 */
				for (ActionConsumer<? extends AbstractAction> consumer : consumers) {
					logger.info("consumer: " + consumer.getClass().getName());
					consumer.consumeAction(action);
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public ActionHandler() {
		super();
	}

	public void registerConsumer(Class<? extends AbstractAction> action,
			ActionConsumer<? extends AbstractAction> consumer) {
		List<ActionConsumer<? extends AbstractAction>> consumers = actionConsumers.get(action);
		if (consumers == null) {
			consumers = new ArrayList<ActionConsumer<? extends AbstractAction>>();
			consumers.add(consumer);
			actionConsumers.put(action, consumers);
			return;
		}

		consumers.add(consumer);
	}

}
